package cn.yzy.manager;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.yzy.db.HibernateUtil;
import cn.yzy.db.Keyword;

public class KeywordManager {
	public static void deleteKeyword(String keyName) {
		Session s = HibernateUtil.currentSession();
		s.beginTransaction();
		Keyword key = KeywordManager.getKeywordFromDB(keyName,s);
		s.delete(key);
		s.getTransaction().commit();
	}

	public static boolean isKeywordInDB(String keyName) {
		Session s = HibernateUtil.currentSession();
		s.beginTransaction();
		boolean result=KeywordManager.getKeywordFromDB(keyName,s)==null?false:true;
		s.getTransaction().commit();
		return result;
	}

	private static Keyword getKeywordFromDB(String keyName,Session s) {
		Query q = s
				.createQuery("select k from Keyword k where k.name=:keyName");
		q.setString("keyName", keyName);
		Object result = q.setMaxResults(1).uniqueResult();
		if (result == null) {
			return null;
		}
		return (Keyword) result;
	}

	public static Keyword getKeyword(String name, Session s) {
		Query q=s.createQuery("select k from Keyword k where k.name=:name");
		q.setString("name", name);
		Keyword key=(Keyword)q.uniqueResult();
		return key;
	}

}
